/*
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <http://www.gnu.org/licenses/>.
 */
package org.merak.core.web;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;

import org.merak.core.Application;
import org.merak.core.model.parameter.Parameter;

/**
 * The Upload Value is the filename, since it instances the form field in
 * the browser. It makes filename-oriented the methods getValue(),isFilled(),
 * isNull(), hasValue() and toString() so they are consistent with each other.
 * Otherwise, to get Upload Content, please call getFile(),
 * getInputStream(), getBytes() or getString().
 */

public class WebParameterOctetStream extends Parameter implements WebParameter {

	//~ Attributes ///////////////////////////////////////////////////////////////
	//****************************************************************************
	private final InputStream in;
	private final long        length;

	//~ Constructors /////////////////////////////////////////////////////////////
	//****************************************************************************
	protected WebParameterOctetStream(HttpServletRequest request) {

		super("octet-stream","");
		try {
			// Initialize
			this.in     = request.getInputStream();
			this.length = request.getContentLength();
			// Get File Name
			String header = request.getHeader("content-disposition");
			if (header!=null && header.startsWith("attachment; filename=")) {
				this.setValue( header.substring(21) );
			}
		}
		catch (IOException e) {
			throw new ExceptionInInitializerError(e);
		}

	}

	//~ Methods //////////////////////////////////////////////////////////////////
	//****************************************************************************
	@Override
	public boolean isUpload() {
		return true;
	}
	//****************************************************************************
	@Override
	public String getFileName() {
		return this.getValue();
	}
	//****************************************************************************
	@Override
	public String getFileType() {

		int typeOffset = this.getFileName().lastIndexOf('.');
		return  typeOffset == -1
				? ""
				: this.getFileName().substring(typeOffset+1);

	}
	//****************************************************************************
	@Override
	public boolean hasFileType(String type) {
		return this.getFileName().endsWith(type);
	}
	//****************************************************************************
	@Override
	public long getLength() {
		return this.length;
	}
	//****************************************************************************
	/** Uploads and write the data to a temporary file.
	 * @throws Exception if the temporary file cannot be created or written to the disk */
	@Override
	public File getFile() throws Exception {

		return this.getFile( Application.io.createTempFile(
			this.getFileName() ,
			this.getFileType()
		));

	}
	//****************************************************************************
	/** Uploads and write the data to the specified file.
	 * @throws Exception if the uploaded data cannot be written to the disk */
	@Override
	public File getFile(File file) throws Exception {

		OutputStream out = new FileOutputStream(file);
		this.writeToOutputStrem(out);
		out.close();
		return file;

	}
	//****************************************************************************
	/** Uploads and returns a byte array.
	 * @throws IOException if the uploaded data cannot be written to the byte array */
	@Override
	public byte[] getBytes() {

		try {
			byte[] content = new byte[(int) this.length];
			int    length  = this.in.read(content);
			int    offset  = length;
			while ( length != -1 ) {
				length  = this.in.read(content, offset, length);
				offset += length;
			}
			return content;
		}
		catch (IOException e) {
			throw new RuntimeException(e);
		}

	}
	//****************************************************************************
	/** Uploads and returns an input stream.
	 * @throws IOException if the uploaded data cannot be written to the OutputStream */
	@Override
	public InputStream getInputStream() throws IOException {
		return this.in;
	}
	//****************************************************************************
	/** Uploads and write the data to the specified output stream.
	 * @throws IOException if the uploaded data cannot be written to the OutputStream */
	@Override
	public void writeToOutputStrem(OutputStream out) throws IOException {

		byte[] buffer = new byte[1024];
		int    length = this.in.read(buffer);
		while ( length != -1 ) {
			out.write(buffer,0,length);
			length = this.in.read(buffer);
		}
		out.flush();

	}
	//****************************************************************************
	@Override
	public boolean equals(Object other) {

		if (other==null) return false;
		return (other instanceof WebParameterOctetStream)
		       && ((WebParameterOctetStream)other).hasValue(this.getValue());

	}
	//****************************************************************************
	@Override
	public String toString() {
		return new String(this.getBytes());
	}
	//****************************************************************************

}
